<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="点餐人ID" prop="memberId">
        <el-input
          v-model="queryParams.memberId"
          placeholder="请输入点餐人ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" prop="id" />
      <el-table-column label="点餐人ID" align="center" prop="memberId" />
      <el-table-column label="用餐时间" align="center" prop="diningTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.diningTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)" size="small">
            <dict-tag :options="status" :value="scope.row.status"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="getOrdersInfo(scope.row)" v-hasPermi="['manage:orders:query']">查看详情</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['manage:orders:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['manage:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单列表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="点餐人ID" prop="memberId">
          <el-input v-model="form.memberId" placeholder="请输入点餐人ID" />
        </el-form-item>
        <el-form-item label="用餐时间" prop="diningTime">
          <el-date-picker
            clearable
            v-model="form.diningTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择用餐时间"
            :shortcuts="dateShortcuts"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情对话框 -->
    <el-dialog 
      title="订单详情" 
      v-model="ordersInfoOpen" 
      width="600px" 
      append-to-body
      destroy-on-close
    >
      <div class="order-detail-container">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单ID">
            <span class="detail-text">{{ form.id }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="点餐人">
            <span class="detail-text">{{ form.memberId }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="点单菜品">
            <span class="detail-text">{{ form.dishesName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="用餐时间">
            <span class="detail-text">{{ parseTime(form.diningTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(form.status)" size="small">
              <dict-tag :options="status" :value="form.status"/>
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注信息">
            <span class="detail-text">{{ form.remark || '暂无备注' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/manage/orders"

const { proxy } = getCurrentInstance()
const { status } = proxy.useDict('status')

const ordersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberId: null,
    status: null,
  },
  rules: {
    memberId: [
      { required: true, message: "点餐人ID不能为空", trigger: "blur" }
    ],
    diningTime: [
      { required: true, message: "用餐时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询订单列表列表 */
function getList() {
  loading.value = true
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    memberId: null,
    diningTime: null,
    remark: null,
    status: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("ordersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单列表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改订单列表"
  })
}

/** 查看详情按钮操作 */
const ordersInfoOpen = ref(false)
function getOrdersInfo(row) {
  reset()
  const _id = row.id
  getOrders(_id).then(response => {
    form.value = response.data
    ordersInfoOpen.value = true
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单列表编号为"' + _ids + '"的数据项？').then(function() {
    return delOrders(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

// 获取订单状态对应的标签类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'warning',  // 待接单
    2: 'primary',  // 待烹饪
    3: 'success',  // 已完成
    4: 'danger'    // 已取消
  };
  return statusMap[status] || 'info';
};

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '明天',
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: '一周后',
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
      return date;
    },
  }
];

getList()
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.detail-text {
  color: #606266;
  font-size: 14px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__cell) {
  padding: 16px 24px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
  color: #303133;
  background-color: #fafafa;
  min-width: 120px;
}

:deep(.el-tag) {
  font-weight: normal;
}
</style>
